/* eslint-disable no-undef */
import { AlexMsg } from '@2473o/alexui'
import axios from 'axios'

const http = axios.create({
  baseURL: '/prod-api/',
  timeout: 5000
})

http.interceptors.request.use(
  (config) => {
    if (!config.headers['Content-Type']) {
      config.headers['Content-Type'] =
        'application/json;charset=UTF-8'
    }

    // localStorage.setItem("user", "user")
    if (localStorage.getItem('token')) {
      config.headers['Authorization'] =
        localStorage.getItem('token')
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

http.interceptors.response.use(
  (response) => {
    if (response.data.code == 401) {
      AlexMsg({
        text: response.data.msg,
        type: 'error'
      })
      window.location.href = '/manage/login'
    }
    return response
  },
  (error) => {
    // console.log('拦截响应失败')
    let { message } = error
    if (message.includes('timeout')) {
      message = '系统接口请求超时'
    }
    AlexMsg({
      text: message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
export default http
